<?php
    class FileGameController extends Controller
    {
        public $layout = false;

        public function actionIndex()
        {
            $gameId = isset($_GET["gameId"]) ? intval($_GET["gameId"]) : 0;
            $extension = isset($_GET["extension"]) ? Common::cleanQuery($_GET["extension"]) : "";
            $userId = isset($_GET["userId"]) ? intval($_GET["userId"]) : 0;              

            $game = GameFile::getGameInfo($gameId);
            $file = GameFile::getGameFileByExtension($gameId, $extension);
            $user = User::getUserInfo($userId);    

            if(!empty($file) && !empty($game) && !empty($user)){
                $username =  $user["username"];
                $this->render("index", array("game"=>$game, "file"=>$file, "username"=>$username,"userId"=>$userId));    
            } else {
                echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                echo "Link không tồn tại";   
            }       
        }

        public function actionDownload()
        {
            $gameId = isset($_GET["gameId"]) ? intval($_GET["gameId"]) : 0;
            $userId = isset($_GET["userId"]) ? intval($_GET["userId"]) : 0;
            $extension = isset($_GET["extension"]) ? Common::cleanQuery($_GET["extension"]) : "";
            $user = User::getUserInfo($userId);
            $game = GameFile::getGameInfo($gameId);

            if(!empty($gameId) && !empty($game) && !empty($user)){   
                $username =   $user["username"];
                $refcode = $user["refCode"];
                // check extension
                if(!empty($extension)) {
                    switch ($extension){
                        case "jar":
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension);
                        case "jad":
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension);
                        case "apk":
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension);
                        case "ipa":
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension);
                            break;
                        default:
                            $url = $this->getFileGameByExtension($game,$userId,$username,"jar");
                            break;
                    }
                }else{
                    // detech device
                    $detect = new Mobile_Detect;
                    $url = Url::createUrl("/fileGame/index", array("userId"=>$userId, "alias"=>$game["alias"], "gameId"=>$game["id"]));  
                    if($detect->isMobile()){
                        // check ios
                        $check = $detect->{'is'."iOS"}();
                        if($check){
                            $extension = "ipa" ;
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension);
                            $arr = explode(".",$url);
                            $arr[count($arr)-1] ="plist";
                            $url=implode(".",$arr); 
                            $url="itms-services://?action=download-manifest&amp;url=".$url;
                            $file = GameFile::getGameFileByExt($gameId,$extension);
                        }

                        // check apk
                        $check = $detect->{'is'."AndroidOS"}();
                        if($check){
                            $extension = "apk" ;
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension);
                            $file = GameFile::getGameFileByExt($gameId,$extension);   
                        }
                        // check java
                        $check = $detect->{'is'."JavaOS"}();
                        if($check){
                            $extension = "jar" ;
                            $url = $this->getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension); 
                            $file = GameFile::getGameFileByExt($gameId,$extension);  
                        }
                        // check java
                        $check = $detect->{'is'."WindowsPhoneOS"}();
                        if($check){

                        }
                        if(!empty( $file['filename'])){  
                            $this->redirect($url);   
                        }else{
                            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                            echo "Link không tồn tại";  die; 
                        }
                    }
                }
                $this->redirect($url);   

            }else{
                echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                echo "Link không tồn tại";   
            }
        }

        public function actionDownloadFile()
        {
            $fileId = isset($_GET["fileId"]) ? intval($_GET["fileId"]) : 0;
            $userId = isset($_GET["userId"]) ? intval($_GET["userId"]) : 0;
            $user = User::getUserInfo($userId);   
            $file = GameFile::getGameFileById($fileId);
            if(!empty($fileId)  && !empty($file) &&!empty($user)){
                /* update count download file */
                $result = GameFile::UpdateDownload($file["gameId"], $file["id"]);
                $url_file = Common::getImageDomain($file["filename"],"user/" . $user["username"] . "/game","","",0);
                $folderJarDes = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$user["username"]."/game/";
                $fileSource = ConstantsUtil::DOCUMENT_ROOT.Common::getFileLocal($file["filename"], "game",$file["create_date"], "",3);
                $fileGameBuild = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$user["username"]."/game/".$file["filename"];
                 
                if(!file_exists( $fileGameBuild )){
                    $extension = substr(strrchr($file["filename"], "."), 1);
                    $filename_response = substr($file["filename"],0,strrpos($file["filename"],"."));

                    switch ($file["extension"]){
                        case "jar":
                            BuildGame::buildFileJava($fileSource,$folderJarDes,$file['gameId'],$user['refCode'],$file["filename"],$user["username"],1);
                            break;
                        case "jad":
                            BuildGame::buildFileJad($fileSource,$folderJarDes,$file['gameId'],$user['refCode'],$file["filename"],$user["username"],1);
                            break;
                        case "apk":
                            BuildGame::buildAppAPK($fileSource,$folderJarDes,$file['gameId'],$file["filename"],$user["username"],$user['refCode']);
                            break;
                        case "ipa":
                            BuildGame::buildAppIPA($fileSource,$folderJarDes,$file['gameId'],$file["filename"],$user["username"],$user['refCode']);
                            break;
                    }

                    //BuildFile::downloadFile($url_file,$filename_response,$extension);
                    $this->redirect($url_file);   
                }else{
                    $this->redirect($url_file);
                }
            } else {
                echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                echo "Link không tồn tại";   
            }        
        }

        function getFileGame($gameId, $os, $username)
        {       
            $game = GameFile::getGameInfo($gameId);
            $file = GameFile::getGameFile($gameId, $os);
            $file = isset($file[0]) ? $file[0]: false;

            if($file){
                $result = GameFile::UpdateDownload($gameId, $file["id"]);
                $url_file = Common::getImageDomain($file["filename"],"user/" . $username . "/game", "", "", 2);

                if($file["extension"]=="plist"){            
                    $link_download = "itms-services://?action=download-manifest&url=" . $url_file;                                                
                    $this->redirect($link_download);
                    exit();
                }

            }else{
                $url_file = Url::createUrl("/fileGame/index", array("username"=>$username, "os"=>$os, "alias"=>$game["alias"], "gameId"=>$game["id"]));
            }
            return $url_file; 

        }

        function getFileGameByExtension($game,$userId,$username,$gameId,$refcode,$extension){
            $rowGameFiles = GameFile::getAllGameFileByExt($game["id"],$extension);
            $url = Url::createUrl("/fileGame/index", array("username"=>$username, "alias"=>$game["alias"], "gameId"=>$game["id"]));  

            if(count($rowGameFiles)>=1){
                // have one file
                if(count($rowGameFiles)==1)
                {
                    $filename =  $rowGameFiles[0]["filename"];
                    $url = Common::getImageDomain($filename, "user/" . $username . "/game", "", "", 2);     
                    $folderJarDes = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$username."/game/";
                    $fileSource = ConstantsUtil::DOCUMENT_ROOT.Common::getFileLocal($rowGameFiles[0]["filename"], "game",$rowGameFiles[0]["create_date"], "",3);
                    $appId=$game['id'];
                    $fileGameBuild = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$username."/game/".$filename;
                    
                    if(!file_exists( $fileGameBuild )){
                        $extension = substr(strrchr($filename, "."), 1);
                        $filename_response = substr($filename,0,strrpos($filename,"."));
                        switch ($rowGameFiles[0]["extension"]){
                            case "jar":
                                BuildGame::buildFileJava($fileSource,$folderJarDes,$appId,$refcode,$filename,$username,1);
                                break;
                            case "jad":
                                BuildGame::buildFileJad($fileSource,$folderJarDes,$appId,$refcode,$filename,$username,1);
                                break;
                            case "apk":
                                BuildGame::buildAppAPK($fileSource,$folderJarDes,$appId,$filename,$username,$refcode);
                                break;
                            case "ipa":
                                BuildGame::buildAppIPA($fileSource,$folderJarDes,$appId,$filename,$username,$refcode);
                                break;
                        }

                    } 
                }else{
                    $url = Url::createUrl("/fileGame/index", array("userId"=>$userId,"extension"=>$extension, "alias"=>$game["alias"], "gameId"=>$game["id"]));
                }
            }

            return   $url;
        }
    } 
?>
